using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Jaws.Core.Web.Data;

namespace Jaws.Core.Web.Entities.Users
{
    /// <summary>
    /// Contains a collection of <see cref="User" />
    /// </summary>
    [Serializable]
    [XmlRoot("users")]
    [XmlDataDirectory("users")]
    public class UserCollection : XmlCollectionBase<UserCollection,User>
    {
        private static UserCollection users = new UserCollection();
        private readonly object _lockObject = new object();

        /// <summary>
        /// Initializes a new instance of the <see cref="UserCollection"/> class.
        /// </summary>
        public UserCollection()
        {
        }

        internal UserCollection(IList<User> array)
            : base(array)
        {
        }

        /// <summary>
        /// Finds the name of the by user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public User FindByUserName(string userName)
        {
            foreach (User u in this)
            {
                if (string.Compare(u.UserName, userName, true, CultureInfo.CurrentCulture) == 0)
                {
                    return u;
                }
            }

            return null;
        }

        /// <summary>
        /// Finds the by email.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <returns></returns>
        public User FindByEmail(string email)
        {
            foreach (User u in this)
            {
                if (string.Compare(u.Email, email, true, CultureInfo.CurrentCulture) == 0)
                {
                    return u;
                }
            }
            return null;
        }

        /// <summary>
        /// Finds the by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public User FindByKey(Guid key)
        {
            foreach (User u in this)
            {
                if (u.Key.Equals(key))
                {
                    return u;
                }
            }
            return null;
        }

        /// <summary>
        /// Finds all active users.
        /// </summary>
        /// <returns></returns>
        public UserCollection FindAllActiveUsers()
        {
            var allActiveUsers = new UserCollection();

            foreach (User u in this)
            {
                if (u.IsActive)
                {
                    allActiveUsers.Add(u);
                }
            }

            return allActiveUsers;
        }
    }
}